package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service // 交给IOC容器管理
public class UserServiceImpl implements UserService {


    //将路径抽取出来, 比较规范, 一般不写死
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO dto) {
        /*//1.通过HttpClient, 构造登录凭证校验请求
        //构造请求参数
        Map<String, String> paramMap  = new HashMap<String, String>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        //调用HttpClient工具类, 发送请求
        String res = HttpClientUtil.doGet(WX_LOGIN_URL, paramMap);
        //输出展示
        log.info("res={}",res);
        //2.解析响应结果, 获取openid
        //返回的res就是结果字符串, 转成json, 才能更好获取openid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");*/

        //直接调用方法
        String openid = getOpenid(dto.getCode());


        //判断, 如果oopenid为null,就不往下走了
        if (openid == null){
            //为什么是用户未登录, 登录是由第三方说的算, 获取到openid, 证明登录成功了
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        //3.判断是否为新用户, 根据openid
        User user = userMapper.selectByOpenid(openid);
        //4.如果是新用户, 初始化用户数据到user表中
        if (user == null){
            //证明是新用户
            //方式一:
            user = User
                    .builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .name(openid.substring(0,5))
                    .build(); // 注意得创建出来, 才能使用里面的方法
            //方式二: 使用get与set方式

            //将数据存入数据库
            userMapper.insert(user);

        }
        //5.否则, 直接返回user对象数据
        return user;
    }

    /**
     * 获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //1.通过HttpClient, 构造登录凭证校验请求
        //构造请求参数
        Map<String, String> paramMap  = new HashMap<String, String>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String res = HttpClientUtil.doGet(WX_LOGIN_URL, paramMap);
        //输出展示
        log.info("res={}",res);
        //2.解析响应结果, 获取openid
        //返回的res就是结果字符串, 转成json, 才能更好获取openid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
